//
//  BBLaunchAdMonitor.m
//  Search
//
//  Created by iXcoder on 15/4/22.
//  Copyright (c) 2015年 iXcoder. All rights reserved.
//

#import "BBLaunchAdMonitor.h"

static BBLaunchAdMonitor *monitor = nil;

@interface BBLaunchAdMonitor()<NSURLConnectionDataDelegate, NSURLConnectionDelegate> {

}

@property (nonatomic, strong) ClickBlock clickBlock;

@property (nonatomic, assign) dispatch_source_t cancletTimer;
@property (nonatomic, assign) BOOL canClick;

@end


@implementation BBLaunchAdMonitor

+ (void)showAdAtPath:(NSString *)path
              onView:(UIView *)container
        timeInterval:(NSTimeInterval)interval
             isClick:(BOOL)isClick
          clickBlock:(ClickBlock)clickBlock{
    
    if (![self validatePath:path]) {
        return ;
    }
    [BBLaunchAdMonitor defaultMonitor].clickBlock = clickBlock;
    [self showImageOnView:container path:path forTime:interval isClick:isClick clickBlock:clickBlock];
}

+ (instancetype)defaultMonitor
{
    @synchronized (self) {
        if (!monitor) {
            monitor = [[BBLaunchAdMonitor alloc] init];
        }
        return monitor;
    }
}

+ (BOOL)validatePath:(NSString *)path
{
    NSURL *url = [NSURL URLWithString:path];
    return url != nil;
}

+ (void)showImageOnView:(UIView *)container
                   path:(NSString *)path
                forTime:(NSTimeInterval)time
                isClick:(BOOL)isClick
             clickBlock:(void (^)(BOOL stop))clickBlock {
    [BBLaunchAdMonitor defaultMonitor].canClick = isClick;
    CGRect f = [UIScreen mainScreen].bounds;
    UIView *v = [[UIView alloc] initWithFrame:f];
    v.backgroundColor = [UIColor whiteColor];
    //f.size.height -= 50;
    CGSize viewSize = DEF_WINDOW.bounds.size;
    NSString *viewOrientation = @"Portrait";    //横屏请设置成 @"Landscape"
    NSString *launchImage = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    UIImageView *iv = [[UIImageView alloc] initWithFrame:f];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImage = dict[@"UILaunchImageName"];
            [iv sd_setImageWithURL:[NSURL URLWithString:path]placeholderImage:[UIImage imageNamed:launchImage]];
        }
    }
    if (isClick) {
        iv.userInteractionEnabled = YES;
    }
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showAdDetail:)];
    [iv addGestureRecognizer:tap];
    iv.contentMode = UIViewContentModeScaleToFill;
    iv.clipsToBounds = YES;
    [v addSubview:iv];
    [container addSubview:v];
    [container bringSubviewToFront:v];
    UIButton *showDetailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [showDetailBtn setTitle:@"跳过 3s" forState:UIControlStateNormal];
    showDetailBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [showDetailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    showDetailBtn.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.5];;
    showDetailBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    showDetailBtn.frame = CGRectMake(f.size.width - 80, 30, 70, 30);
    showDetailBtn.tag = 888;
    [showDetailBtn addTarget:self action:@selector(showAdDetail:) forControlEvents:UIControlEventTouchUpInside];
    [v addSubview:showDetailBtn];
    __block int timeout=3; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    [BBLaunchAdMonitor defaultMonitor].cancletTimer = _timer;
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //djsLabel.text = @"0s";
                iv.userInteractionEnabled = NO;
                showDetailBtn.userInteractionEnabled = NO;
                [showDetailBtn setTitle:@"跳过广告" forState:UIControlStateNormal];
                [BBLaunchAdMonitor defaultMonitor].clickBlock(YES);
            });
        }else{
            //            int minutes = timeout / 60;
            int second = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", second];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [showDetailBtn setTitle:[NSString stringWithFormat:@"跳过 %@s",strTime] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
    //UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, f.size.height + 10, f.size.width - 20, 30)];
//    label.backgroundColor = [UIColor clearColor];
//    label.text = @"©2015 iXcoder. All Rights Reserved";
//    label.textAlignment = NSTextAlignmentCenter;
//    label.font = [UIFont systemFontOfSize:15];
//    [v addSubview:label];
//    label = nil;
    
    [container addSubview:v];
    
    if (![BBLaunchAdMonitor defaultMonitor].canClick) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self removeImg:v imgView:iv];
        });
    }
}

+ (void)removeImg:(UIView *)v imgView:(UIImageView *)iv{
    v.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.75 animations:^{
        iv.transform = CGAffineTransformMakeScale(2.f, 2.f);
        v.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [v removeFromSuperview];
    }];
}

+ (void)showAdDetail:(id)sender {
    UIView *sup;
    if ([sender isKindOfClass:[UIButton class]]) {
        [BBLaunchAdMonitor defaultMonitor].clickBlock(YES);
        if ([BBLaunchAdMonitor defaultMonitor].cancletTimer) {
            
            dispatch_source_cancel([BBLaunchAdMonitor defaultMonitor].cancletTimer);
        }
        sup = [sender superview];
        [UIView animateWithDuration:0.25
                         animations:^{
                             sup.alpha = 0.0f;
                         }
                         completion:^(BOOL finished) {
                             [sup removeFromSuperview];
                         }];
    } else {
        UITapGestureRecognizer * tap = (UITapGestureRecognizer *)sender;
        [BBLaunchAdMonitor defaultMonitor].clickBlock(NO);
        if ([BBLaunchAdMonitor defaultMonitor].canClick) {
            if ([BBLaunchAdMonitor defaultMonitor].cancletTimer) {
                dispatch_source_cancel([BBLaunchAdMonitor defaultMonitor].cancletTimer);
                [self removeImg:tap.view.superview imgView:tap.view];
            }
        }
        sup = tap.view.superview;
    }
    sup.userInteractionEnabled = NO;

}

@end

